package Queue_and_Stack;

/*
岛屿数量
给你一个由'1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外，你可以假设该网格的四条边均被水包围。
示例 1：
输入：grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
输出：1
示例 2：
输入：grid = [
  ["1","1","0","0","0"],
  ["1","1","0","0","0"],
  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
输出：3
作者：LeetCode
链接：https://leetcode.cn/leetbook/read/queue-stack/kbcqv/
 */

import java.util.*;

public class _21岛屿数量 {
    public static void main(String[] args) {

    }

    //BFS  模拟
    //代码并不需要HashSet进行去重，因为代码中已经提前对四周的'1'更改为'0',等同于进行了HashSet去重
    //如果添加了HashSet去重，会拖慢代码运行速度 -- 20ms
    //8ms
    //O(MN)  O(min(M,N))
    public int numIslands(char[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int count = 0;
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    queue.offer(new int[]{i, j});
                    while (!queue.isEmpty()) {
                        int x = queue.peek()[0];
                        int y = queue.peek()[1];
                        int up = x - 1 == -1 ? 0 : x - 1;
                        int down = x + 1 == m ? x : x + 1;
                        int right = y + 1 == n ? y : y + 1;
                        int left = y - 1 == -1 ? 0 : y - 1;
                        grid[x][y] = '0';
                        if (grid[x][right] == '1') {
                            queue.offer(new int[]{x, right});
                            grid[x][right] = '0';  //进一步节省时间
                        }
                        if (grid[x][left] == '1') {
                            queue.offer(new int[]{x, left});
                            grid[x][left] = '0';
                        }
                        if (grid[up][y] == '1') {
                            queue.offer(new int[]{up, y});
                            grid[up][y] = '0';
                        }
                        if (grid[down][y] == '1') {
                            queue.offer(new int[]{down, y});
                            grid[down][y] = '0';
                        }
                        queue.remove();
                    }
                }
            }
        }
        return count;
    }

    //官解：BFS(广度优先搜索)
    //与我不同的是 在队列的增加上官方采用了二维数组通过id进行一维化，即采用了数学上的计算，只需要id便可以计算出每个数据对应的x,y数组坐标
    //7ms
    //O(MN)  O(min(M,N))   为啥是min(M,N)呢？ 因为不同于递归会一直占用空间，队列会remove,因而空间最大为min(M,N)
    class Solution {
        public int numIslands(char[][] grid) {
            if (grid == null || grid.length == 0) {
                return 0;
            }

            int nr = grid.length;
            int nc = grid[0].length;
            int num_islands = 0;

            for (int r = 0; r < nr; ++r) {
                for (int c = 0; c < nc; ++c) {
                    if (grid[r][c] == '1') {
                        ++num_islands;
                        grid[r][c] = '0';
                        Queue<Integer> neighbors = new LinkedList<>();
                        neighbors.add(r * nc + c);
                        while (!neighbors.isEmpty()) {
                            int id = neighbors.remove();
                            int row = id / nc;
                            int col = id % nc;
                            if (row - 1 >= 0 && grid[row-1][col] == '1') {
                                neighbors.add((row-1) * nc + col);
                                grid[row-1][col] = '0';
                            }
                            if (row + 1 < nr && grid[row+1][col] == '1') {
                                neighbors.add((row+1) * nc + col);
                                grid[row+1][col] = '0';
                            }
                            if (col - 1 >= 0 && grid[row][col-1] == '1') {
                                neighbors.add(row * nc + col-1);
                                grid[row][col-1] = '0';
                            }
                            if (col + 1 < nc && grid[row][col+1] == '1') {
                                neighbors.add(row * nc + col+1);
                                grid[row][col+1] = '0';
                            }
                        }
                    }
                }
            }

            return num_islands;
        }
    }

    //官解：深度优先搜索
    //递归
    //思路跟广度优先搜索差不多
    //效果数据大小比较小的时候可以用空间换时间
    //2ms
    //O(MN)  O(MN)
    class Solution2 {
        void dfs(char[][] grid, int r, int c) {
            int nr = grid.length;
            int nc = grid[0].length;

            if (r < 0 || c < 0 || r >= nr || c >= nc || grid[r][c] == '0') {
                return;
            }

            grid[r][c] = '0';
            dfs(grid, r - 1, c);
            dfs(grid, r + 1, c);
            dfs(grid, r, c - 1);
            dfs(grid, r, c + 1);
        }

        public int numIslands(char[][] grid) {
            if (grid == null || grid.length == 0) {
                return 0;
            }

            int nr = grid.length;
            int nc = grid[0].length;
            int num_islands = 0;
            for (int r = 0; r < nr; ++r) {
                for (int c = 0; c < nc; ++c) {
                    if (grid[r][c] == '1') {
                        ++num_islands;
                        dfs(grid, r, c);
                    }
                }
            }

            return num_islands;
        }
    }





}
